package retryer;

import com.github.rholder.retry.Retryer;
import com.github.rholder.retry.RetryerBuilder;
import com.github.rholder.retry.StopStrategies;
import com.github.rholder.retry.WaitStrategies;
import com.google.common.base.Predicates;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName : CustomizeRetryer
 * @Description : 全局自定义重试器
 * @Author : gyh
 * @Date: 2022-01-08 17:59
 */
@Component
public class CustomizeRetryer {
    //定义发送邮件的重试器
    private Retryer<Boolean> mailRetryer;

    //定义发送短信的重试器
    private Retryer<Boolean> msgRetryer;

    @Bean(value = "mailRetryer")
    public Retryer mailRetryer() {
        mailRetryer = RetryerBuilder.<Boolean>newBuilder()
                //retryIf 重试条件
                .retryIfException()
                .retryIfRuntimeException()
                .retryIfExceptionOfType(Exception.class)
                .retryIfException(Predicates.equalTo(new Exception()))
                .retryIfResult(Predicates.equalTo(false))
                //等待策略：每次请求间隔1s
                .withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS))
                //停止策略 : 尝试请求6次
                .withStopStrategy(StopStrategies.stopAfterAttempt(6))
                .build();
        return mailRetryer;
    }

    @Bean(value = "msgRetryer")
    public Retryer msgRetryer() {
        msgRetryer = RetryerBuilder.<Boolean>newBuilder()
                //retryIf 重试条件
                .retryIfException()
                .retryIfRuntimeException()
                .retryIfExceptionOfType(Exception.class)
                .retryIfException(Predicates.equalTo(new Exception()))
                .retryIfResult(Predicates.equalTo(false))
                //等待策略：每次请求间隔0.2秒
                .withWaitStrategy(WaitStrategies.fixedWait(200, TimeUnit.MILLISECONDS))
                //停止策略 : 尝试请求9次
                .withStopStrategy(StopStrategies.stopAfterAttempt(9))
                .build();
        return msgRetryer;
    }

//    public static void main(String[] args) {
//        //使用
//        mailRetryer.call(() -> {
//            try {
//                // 处理业务
//                //handleService();
//                return true;
//            } catch (Exception e) {
//                return false;
//            }
//        });
//    }
}


